from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.hashers import check_password
import json
from my1.models import UserData
from django.db.models import Q
import uuid


@csrf_exempt
def login(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            login_id = data.get('username')  # 可以是username或email
            password = data.get('password')

            # 从数据库验证用户
            user = UserData.objects.filter(
                Q(username=login_id) | Q(email=login_id)
            ).first()

            if user:
                # 验证密码
                if check_password(password, user.password):
                    # 获取关联的店铺信息
                    shop_id = user.shop_id
                    shop_name = ""

                    # 通过shop_id获取店铺名称
                    try:
                        from my1.models import Shop
                        shop = Shop.objects.get(id=shop_id)
                        shop_name = shop.name
                    except Exception as e:
                        print(f"获取店铺名称失败: {str(e)}")
                        shop_name = f"店铺{shop_id}"  # 默认名称

                    return JsonResponse({
                        'success': True,
                        'status': 'success',
                        'token': str(uuid.uuid4()),
                        'user': {
                            'username': user.username,
                            'shop_id': shop_id,
                            'shop_name': shop_name  # 同时返回店铺名称
                        },
                        'message': '登录成功'
                    })
                else:
                    print(f"密码验证失败 - 用户: {login_id}")

            # 如果验证失败
            return JsonResponse({
                'success': False,
                'status': 'error',
                'message': '用户名或密码错误'
            })

        except Exception as e:
            print(f"登录过程中出错: {str(e)}")
            return JsonResponse({
                'success': False,
                'status': 'error',
                'message': f'登录过程中出错: {str(e)}'
            })

    return JsonResponse({
        'success': False,
        'status': 'error',
        'message': '不支持的请求方法'
    })